
import TCheckbox  from 't/basic/checkbox';
import TPopupProxy from 't/basic/popup-proxy';
import TButton from 't/basic/button';
import TTable from 't/basic/table';
import TTr from 't/basic/table/Tr';
import TTh from 't/basic/table/Th';
import TTd from 't/basic/table/Td';
import noDataPlaceholder from './no-data-placeholder.vue';
import { useQuasar } from '@teld/q-components';
import TPrefabPagination from 't/bussiness/prefab-pagination';
import {
  computed,
  defineComponent,
  inject,
  nextTick,
  ref,
  toRefs,
  watch,
} from 'vue';
import HistoryComponent from './HistoryComponent';
import SingleRow from './SingleRow';
export default defineComponent({
  name: 'SelectHelperBigSizeRender',
  components: {
    TPopupProxy,
    TTable,
    HistoryComponent,
    SingleRow,
    TCheckbox,
    TButton,
    TTr,
    TTh,
    TTd,
    noDataPlaceholder,
    TPrefabPagination
  },
  props: {
    simple: {
      type: Boolean,
      default: true,
    },
    width: {
      type: [String, Number],
      default: '1',
    },
    multiple: Boolean,
    historyEnable: Boolean,
    dropDownWidth: String,
    countPerPage: [String, Number],
    pagination: Boolean,
    checkList: {
      type: [Array, String, Object],
    },
    columns: {
      type: Array,
    },
    valueField: String,
    labelField: String,
    helperCode: String,
    filter: String,
    dropWidth: String,
    iconEnable: Boolean,
    iconDataSource: String,
    iconFiled: String,
    instanceCode: String,
    pageSizeRange:Array,
    maxCountPerPage:[String,Number],
    isMultiseriate:Boolean,
    columnNumber:Number,
    dropPosition:String,
    columnarPattern:Boolean,
  },
  emits: ['update:checkList', 'close', 'update:filter'],
  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const $q = useQuasar();
    const {
      simple,
      width,
      multiple,
      historyEnable,
      dropDownWidth,
      dropWidth,
      checkList,
      columns,
      valueField,
      labelField,
      helperCode,
      filter,
      countPerPage,
      pagination,
      iconEnable,
      iconDataSource,
      iconFiled,
      instanceCode,
      pageSizeRange,
      maxCountPerPage,
      isMultiseriate,
      columnNumber,
      dropPosition,
      columnarPattern
    } = toRefs(props);
    const isShow = ref(false);
    const getCaption = (caption, value) => {
      if(value){
        return Funcs.GetTerms(value.ReferenceExpr,caption)
      }else{
        return caption
      }
    }
    const columnsByComputed = computed(() => {
      return columns.value
        .map(item => {
          if (item.isShow) {
            return {
              name: item.dataField,
              required: true,
              label: getCaption(item.caption,item.ValueInfo_caption),
              align: item.textAlign ? item.textAlign : 'left',
              field: item.dataField,
              width: item.width ? item.width : '',
            };
          }
        })
        .filter(item => item);
    });
    const rows = ref([]);
    const refTPopupProxy = ref(null);
    const selection = ref([]);

    const show = () => {
      refTPopupProxy.value && refTPopupProxy.value.show();
    };
    const close = () => {
      refTPopupProxy.value && refTPopupProxy.value.hide();
    };
    const getDateByFilter = () => {
      let _rows;
      if (simple.value) {
        _rows = refComponent.value.getDateByFilter();
      } else {
        _rows = rows.value;
      }
      if (_rows && _rows.length == 1) {
        if (
          !selectList.value.some(
            item => item[valueField.value] == _rows[0][valueField.value],
          )
        ) {
          selectList.value.push(_rows[0]);
        }
        emit('update:checkList', selectList.value);
      }
    };
    expose({
      show,
      hide: close,
      close,
      getDateByFilter,
      isShow,

    });
    const tableRef = ref(null);
    // onMounted(async () => {
    //   await nextTick();
    //   setTimeout(() => {
    //     if (tableRef.value) {

    //     }
    //   }, 3000);
    // });
    //已选择数据集合
    const selectList = ref([]);
    function onClickHandler(params) {}
    //简单模式
    const generateSimple = () => {
      return (
        <single-row
        columnarPattern={columnarPattern.value}
        dropPosition={dropPosition.value}
          isMultiseriate={isMultiseriate.value}
         columnNumber={columnNumber.value}
          class='select_helper_popup_content'
          ref={refComponent}
          width={width.value + 'px'}
          multiple={multiple.value}
          simple={simple.value}
          labelField={labelField.value}
          valueField={valueField.value}
         filter={filter.value}
          onUpdate:filter={(e)=>{emit('update:filter',e)}}
          pagination={pagination.value}
          countPerPage={countPerPage.value}
          onUpdateSelectList={e => {
            if (!multiple.value) {
              close();
              filter.value = '';
            }

            selectList.value = e;
            if(!(columnarPattern.value&&multiple.value)){
              emit('update:checkList', e);
            }
            // emit('update:checkList', e);
          }}
          targetSelection={selection.value}
          targetSelectList={selectList.value}
          iconEnable={iconEnable.value}
          iconDataSource={iconDataSource.value}
          onClose={close}
          onLoadData={searchByFilterFn}
        />
      );
    };
    const selectList_proxy = ref([]);
    watch(
      () => checkList.value,
      () => {
        //计算当前数据，实现数据回显
        if (!simple.value) {
          selectList_proxy.value = checkList.value;
          selectList.value = JSON.parse(JSON.stringify(selectList_proxy.value));
        } else {
          selectList.value = checkList.value;
        }
      },
      {
        deep: true,
        immediate: true,
      },
    );
    //定义点击事件
    const trTargetClick = target => {
      if (
        selectList.value.some(
          item => item[valueField.value] == target[valueField.value],
        )
      ) {
        selectList.value = selectList.value.filter(
          item => item[valueField.value] != target[valueField.value],
        );
      } else {
        if (!multiple.value) {
          selectList.value = [];
        }
        selectList.value.push(target);
      }
    };
    const PageSizeRange = computed(() => {
      let returnValue =pageSizeRange.value?pageSizeRange.value: [10, 20, 50, 100, 150, 500, 1000];

      let pSize = countPerPag_s;
      if (false == returnValue.includes(+pSize)) {
        returnValue.push(pSize);
        returnValue = _.uniq(returnValue);
        returnValue = _.sortBy(returnValue);
      }
      if(maxCountPerPage.value){
        returnValue = returnValue.filter(item=>item<=maxCountPerPage.value)
      }
      return returnValue;
    });

    const checkAll = computed(() => {
      if (
        rows.value.every(item =>
          selection.value.some(sel => item[valueField.value] == sel),
        )
      ) {
        return ['ischecked'];
      } else if (
        !rows.value.some(item =>
          selection.value.some(sel => item[valueField.value] == sel),
        )
      ) {
        return [];
      }
      return null;
    });
    if (multiple.value) {
      watch(
        () => selectList.value,
        () => {
          selection.value = selectList.value.map(
            item => item[valueField.value],
          );
        },
        {
          deep: true,
          immediate: true,
        },
      );
    }
    let countPerPag_s = pagination.value ? countPerPage.value : null;
    const _pagination = ref({
      sortBy: 'desc',
      descending: false,
      page: 1,
      rowsPerPage: countPerPag_s,
      rowsNumber: 10,
    });
    const searchByFilter = inject('searchByFilter');
    const isLoading = ref(false);
    let isClicking = false;
    let query = '';
    watch(
      () => filter.value,
      (oldValue,newValue) => {
        if(oldValue == newValue) return
        if (query) {
          window.clearTimeout(query);
          query = null;
        }
        query = window.setTimeout(() => {
          if(columnarPattern.value){
            if(!isShow.value) return
            page.value = 1
            searchByFilterFn()
            return
          }
          rows.value = [];
          _pagination.value.page = 1;

          tableRef.value?.requestServerInteraction();
        }, 200);
      },
    );

    // 复杂模式
    const generateComplex = () => {
      return (
        <div
          class='select_helper_popup_content'
          style={
            dropDownWidth.value != 'auto'
              ? `width:${relWidth.value};display: flex; flex-direction: column;flex: 1 1 auto;position:relative`
              : 'min-width:500px;max-width:600px;display: flex; flex-direction: column;flex: 1 1 auto;position:relative'
          }
        >
          {(() => {
            if (historyEnable.value) {
              return (
                <history-component
                  labelField={labelField.value}
                  valueField={valueField.value}
                  helperCode={helperCode.value}
                  filter={filter.value}
                  onClickByTag={e => {
                    if (!multiple.value) {
                      selectList.value = [];
                    }
                    if (
                      selectList.value &&
                      !selectList.value.some(
                        item => item[valueField.value] == e[valueField.value],
                      )
                    ) {
                      selectList.value.push(e);
                    }
                    emit('update:checkList', selectList.value);
                    close();
                  }}
                ></history-component>
              );
            }
          })()}

          <t-table
            style='flex: 1 1 auto;overflow: hidden;min-height: 96px;height:336px'
            class='my-sticky-header-column-table'
            flat
            ref={tableRef}
            rows={rows.value}
            columns={columnsByComputed.value}
            class='select_helper_popup_table'
            v-model:pagination={_pagination.value}
            loading={isLoading.value}
            hideBottom={!pagination.value}
            row-key='name'
            selection='single'
            rows-per-page-options={PageSizeRange.value}
            // style='height:300px'
            onSelection={e => {
              console.log(e);
            }}
            onRequest={async e => {
              //请求
              const { page, rowsPerPage, sortBy, descending } = e.pagination;
              if (_pagination.value.rowsPerPage != rowsPerPage) {
                _pagination.value.page = 1;
              } else {
                _pagination.value.page = page;
              }
              _pagination.value.rowsPerPage = rowsPerPage;
              _pagination.value.sortBy = sortBy;
              _pagination.value.descending = descending;
              isLoading.value = true;
              let res = await searchByFilter(
                _pagination.value.page,
                pagination.value ? _pagination.value.rowsPerPage : 10,
              );
              _pagination.value.rowsNumber = res.Count;
              res.List ? (rows.value = res.List) : (rows.value = []);
              isLoading.value = false;
            }}
          >
            {{
              // 重写一下body&header 处理点击事件
              header: props => {
                return (
                  <t-tr props={props}>
                    {(() => {
                      let Template = [];
                      if (multiple.value) {
                        Template.push(
                          <t-th auto-width>
                            <t-checkbox
                              size='sm'
                              onClick={() => {
                                if (checkAll.value == null) {
                                  selectList.value = selectList.value.filter(
                                    item =>
                                      !rows.value.some(
                                        r =>
                                          r[valueField.value] ==
                                          item[valueField.value],
                                      ),
                                  );
                                } else if (checkAll.value.length == 0) {
                                  selectList.value = selectList.value.concat(
                                    ...rows.value,
                                  );
                                } else {
                                  selectList.value = selectList.value.filter(
                                    item =>
                                      !rows.value.some(
                                        r =>
                                          r[valueField.value] ==
                                          item[valueField.value],
                                      ),
                                  );
                                }
                              }}
                              v-model={checkAll.value}
                              val='ischecked'
                            />
                          </t-th>,
                        );
                      }

                      props.cols.forEach(element => {
                        Template.push(
                          <t-th key={element.name} props={props} {...element}>
                            {element.label}
                          </t-th>,
                        );
                      });
                      return Template;
                    })()}
                  </t-tr>
                );
              },

              body: props => {
                // console.log(props)
                return (
                  <t-tr
                    props={props}

                    onClick={(e) => {
                      if (!isClicking) {
                        trTargetClick(props.row);
                        isClicking = true;
                        window.setTimeout(() => {
                          isClicking = false;
                        }, 300);
                      } else {
                        if (!multiple.value) {
                          if (
                            !selectList.value.some(
                              item => item[valueField.value] == props.row[valueField.value]
                            )
                          ){
                            selectList.value.push(props.row);
                          }
                          emit('update:checkList', selectList.value);
                          if(!window.formEnterKey){
                            close();
                          }else{
                            delete window.formEnterKey
                          }
                          // close();
                        }
                      }
                      e&&e.stopPropagation();
                      e&&e.preventDefault();
                      return false
                    }}
                    // onDblclick={() => {
                    //   trTargetClick(props.row);
                    //   emit('update:checkList', selectList.value);
                    //   close();
                    // }}
                    class={
                      selectList.value.some(
                        item =>
                          item[valueField.value] == props.row[valueField.value],
                      )
                        ? 'select_helper_popup_table_tr_checked'
                        : ''
                    }
                  >
                    {(() => {
                      let Template = [];
                      if (multiple.value) {
                        Template.push(
                          <t-td auto-width>
                            <t-checkbox
                              size='sm'
                              onClick={() => {
                                trTargetClick(props.row);
                              }}
                              v-model={selection.value}
                              val={props.row[valueField.value]}
                            />
                          </t-td>,
                        );
                      }

                      props.cols.forEach(element => {
                        Template.push(
                          <t-td key={element.field} {...element}>
                            <div title={props.row[element.field]} style={`display:flex;align-items:center;justify-content:${element.align};gap:8px;${element.width?'width:'+element.width+';white-space: nowrap;overflow: hidden;text-overflow: ellipsis;':''}`}>
                              {iconEnable.value
                                ? (() => {
                                    if (iconFiled.value == element.field) {
                                      return (
                                        <img
                                          src={props.row[iconDataSource.value]}
                                          style='width:24px;height:24px;border-radius:2px'
                                        />
                                      );
                                    }
                                  })()
                                : ''}
                              {props.row[element.field]}
                            </div>
                          </t-td>,
                        );
                      });
                      // for (let i in props.row) {
                      //   Template.push(
                      //     <t-td key={i} props={props}>
                      //       {props.row[i]}
                      //     </t-td>,
                      //   );
                      // }
                      return Template;
                    })()}
                  </t-tr>
                );
              },
            }}
          </t-table>
          {(()=>{
            if(rows.value.length==0){
              return <noDataPlaceholder text={$q.lang.dataGrid.emptyText} style='position: absolute; top: 150px;left: 0;bottom: 0;right: 0; width: 100%;height: 240px;z-index: 100000000; background: #ffff;' noData={$q.lang.dataGrid.emptyText}> </noDataPlaceholder>
            }
          })()}
          <div class='select_helper_popup_foot'>
            <t-button style='border:1px solid #DCDCDC;' onClick={close}>
              {/* 取消 */}
             {$q.lang.label.cancel}
            </t-button>{' '}
            <t-button
              color='primary'
              onClick={() => {
                console.log(selectList.value);
                selectList_proxy.value = JSON.parse(
                  JSON.stringify(selectList.value),
                );
                emit(
                  'update:checkList',
                  JSON.parse(JSON.stringify(selectList.value)),
                );
                close();
              }}
            >
              {/* 确定 */}
              {$q.lang.label.ok}
            </t-button>
          </div>
        </div>
      );
    };
    const generateCheckedValue = ()=>{
      if(!selectList.value.length){
        return ''
      }
      console.log(selectList.value)
      let template = []
      selectList.value.forEach(item=>{
        template.push(
          <span style={'background:#F3F3F3;border-radius:2px;padding:0 8px;height:24px;display:flex;align-items:center;gap:8px;color:rgba(0,0,0,.8)'}>
            {item[labelField.value]}
            <i onClick={(e)=>{
                selectList.value = selectList.value.filter(i=>i[valueField.value]!=item[valueField.value])
              e.stopPropagation()
            return false
            }} class={'fas dx-icon icon-t-close-circle'} style={'color:rgba(0,0,0,.24);cursor:pointer;font-size:12px'}></i>
          </span>
        )
      })
      return template
    }
    const page = ref(1)
    const _rows = ref(countPerPage.value)
    const total = ref(0)
    let dataLit=[]
    const searchByFilterFn=(resList)=>{

      if(resList){
        dataLit=resList
      }
      searchByFilter(page.value, _rows.value  ||10, filter.value).then(res => {

        console.log(res)
        dataLit.value = res.List
        total.value = res.Count
      });
    }
    //生成内容区域
    const generateContent = () => {
      if (simple.value) {
        return (
          <div style={`width:${isMultiseriate.value?'100vw':(columnarPattern.value&&multiple.value?relWidth.value.replace(/px/gi, '') :width.value.replace(/px/gi, '')) + 'px'}`}>
            {(()=>{
              if(columnarPattern.value&&multiple.value){
                return <div style={'display:flex;padding:0 8px;height:416px;overflow:hidden'}>
                  <div class={'left'} style={`padding:12px 12px 20px 20px;width:320px;display: flex;flex-direction: column;border-right:1px solid #F0F2F5;padding-left:12px`}>
                      {generateSimple()}
                      {(()=>{
                         if(total.value){
                          if(!pagination.value){
                            return ''
                          }
                         return  <>
                    <div style={'margin-top:12px'}>
                    <t-prefab-pagination
                      class={'select_helper_columnarPattern_pagination'}
                      modelValue={page.value}
                      onUpdate:modelValue={(e)=>{
                        page.value = e
                      }}
                      prefab={'perfective'}
                      totals={total.value}
                      v-model:pageSize={_rows.value}
                      maxPages={4}
                      onPageChanged={()=>{
                        searchByFilterFn()
                      }}
                      onPageSizeChanged={()=>{
                        page.value = 1
                        searchByFilterFn()
                      }}
                    ></t-prefab-pagination>
                    </div>
                      </>
                    }else{
                      // return  <noDataPlaceholder noData={$q.lang.dataGrid.emptyText}> </noDataPlaceholder>

                    }
                   })()}

                  </div>
                  <div class={'right'} style={'flex:1;padding:20px 20px;    display: flex;flex-direction: column'}>
                  <div class={'top'} style={'width:100%;display:flex;justify-content:space-between;align-items:start;font-size:14px;color:rgba(0,0,0,.8);;margin-bottom:20px'}>
                      <span>
                        {$q.lang.selectHelper.checked}（{selectList.value.length}）
                      </span>
                      <span style={'cursor:pointer'} onClick={()=>{
                        if(!selectList.value.length){
                          return
                        }
                        Funcs.Confirm($q.lang.selectHelper.warning,$q.lang.selectHelper.clearMessage,()=>{
                          selectList.value = []
                        },()=>{},null,{type:'warning',confirmButtonText:$q.lang.label.clear, customClass:'prevent-click'})

                      }}>
                       <i style={'font-size:14px;color:rgba(0,0,0,.8);margin-right:6px'} class={'fas dx-icon icon-t-delete-outlined'}></i> {$q.lang.label.clear}
                      </span>
                    </div>
                    <div style={'flex: 1;overflow-y:auto'}>

                     <div style={' display: flex;gap: 12px;flex-wrap: wrap;'}>
                     {generateCheckedValue()}
                     </div>

                    </div>
                    <div class='select_helper_popup_foot'>
            <t-button style='border:1px solid #DCDCDC;' onClick={close}>
              {/* 取消 */}
             {$q.lang.label.cancel}
            </t-button>{' '}
            <t-button
              color='primary'
              onClick={() => {
                console.log(selectList.value);
                selectList_proxy.value = JSON.parse(
                  JSON.stringify(selectList.value),
                );
                emit(
                  'update:checkList',
                  JSON.parse(JSON.stringify(selectList.value)),
                );
                close();
              }}
            >
              {/* 确定 */}
              {$q.lang.label.ok}
            </t-button>
          </div>
                  </div>
                </div>
              }else{

                return generateSimple()
              }
            })()}


          </div>
        );
      }
      return generateComplex();
    };

    let relWidth = computed(() => {
      if(columnarPattern.value&& dropDownWidth.value == 'auto'){
        return '720px';
      }
      let _width = dropDownWidth.value == 'auto' ? '600px' : dropWidth.value;
      if (_width.indexOf('%') != -1) {
        _width =
          (_width.replace(/%/gi, '') / 100) * width.value.replace(/px/gi, '') +
          'px';
      } else if (_width.indexOf('px') == -1) {
        _width = _width + 'px';
      }
      return _width;
    });

    return () => {
      return (
        <t-popup-proxy
          ref={refTPopupProxy}
          class={
            simple.value
              ? `select_helper_popup single ${instanceCode.value} ${isMultiseriate.value?('dropPosition_'+dropPosition.value):''}`
              : `select_helper_popup ${instanceCode.value} ${isMultiseriate.value?('dropPosition_'+dropPosition.value):''}`
          }
          style='display: flex;'
          onShow={async () => {
            // const scrollbarWidth =
            //   window.innerWidth - document.documentElement.clientWidth;
            // document.body.style.overflow = 'hidden';
            // document.body.style.paddingRight = `${scrollbarWidth}px`;
            isShow.value = true;
            await nextTick();
            if(!simple.value){
              tableRef.value?.requestServerInteraction();
            }
            // tableRef.value?.requestServerInteraction();
          }}
          onHide={() => {
            // setTimeout(() => {
            //   refTPopupProxy.value.hide();
            // }, 100);

            // document.body.style.overflow = '';
            // document.body.style.paddingRight = '';
            setTimeout(() => {
              isShow.value = false;
            }, 500);

            emit('close');
          }}
        >
          {(() => {
            return generateContent();
          })()}
        </t-popup-proxy>
      );
    };
  },
});
